<?php

namespace app\common\logic;

use app\common\exception\BusinessException;
use app\common\model\CourseQuestion;
use app\common\service\QuestionHashService;

/**
 * 题目服务
 */
class Question
{
    /**
     * save
     * @param $param
     * @throws BusinessException
     */
    public function save($param)
    {
        //提取数据
        $time = time();
        $type = $param['type'];
        $uid = $param['uid'] ?? 0;
        $course_id = $param['course_id'];
        $extend_id = $param['extend_id'] ?? 0;
        $charge_type = $param['charge_type'];
        $question_type = $param['question_type'];
        $question_data = $param['question_data'];
        $background_id = $param['background_id'] ?? 0;

        // 检查参数
        if (!$extend_id) {
            throw new BusinessException("题目所属试卷编号不得为空");
        }

        //提取题目映射
        $model = new CourseQuestion();
        $func = "getType{$question_type}Map";
        if (!method_exists($model, $func)) {
            throw new BusinessException("题目映射结构提取失败,题目类型{$question_type}");
        }
        $question_map = $model->$func();

        // 循环构建数据
        foreach ($question_data as $key => $val) {
            //构建数据
            try {
                // 格式构建
                $input_data = $this->buildQuestionData($key, $val, $question_map);
            } catch (BusinessException $exception) {
                echo $exception->getMessage() . '数据不再处理' . PHP_EOL;
                continue;
            }

            // 检查重复
            $question_hash = QuestionHashService::build($input_data);
            $where = [
                ['type', '=', $type],
                ['course_id', '=', $course_id],
                ['question_type', '=', $question_type],
                ['question_hash', '=', $question_hash]
            ];
            if ($extend_id) {
                $where[] = ['extend_id', '=', $extend_id];
            }
            $count = app(CourseQuestion::class)->where($where)->count();

            // 组装题目
            $insert_data = [
                'uid' => $uid,
                'course_id' => $course_id,
                'extend_id' => $extend_id,
                'type' => $type,
                'charge_type' => $charge_type,
                'question_type' => $question_type,
                'question_name' => $input_data['questionAsk'],
                'question_hash' => $question_hash,
                'question_data' => json_encode($input_data, JSON_UNESCAPED_UNICODE),
                'background_id' => $background_id,
                'platform_question_id' => $val['id'] ?? '',
                'a_time' => $time,
                'u_time' => $time,
            ];

            if (!$count) {
                $isAdd = app(CourseQuestion::class)->add_data($insert_data);
                if (!$isAdd) {
                    throw new BusinessException("新增题目数据失败");
                }
            } else {
                unset($insert_data['a_time']);
                $isAdd = app(CourseQuestion::class)->save_data($insert_data, $where);
                if ($isAdd === false) {
                    throw new BusinessException("更新题目数据失败");
                }
            }
        }
    }

    /**
     * 构建题目数据
     * @param $key
     * @param $val
     * @param $question_map
     * @return array
     * @throws BusinessException
     */
    private function buildQuestionData($key, $val, $question_map): array
    {
        $input_data = [];
        foreach ($question_map as $q_key => $q_val) {
            if (is_array($q_val)) {
                foreach ($q_val as $op_key => $op_val) {
                    if ($op_val && !isset($val[$q_key][$op_key])) {
                        throw new BusinessException("第{$key}条数据{$op_key}字段缺失");
                    }
                    if ($op_val && $val[$q_key][$op_key] == '') {
                        throw new BusinessException("第{$key}条数据{$q_key}_{$op_key}字段不得为空");
                    }
                    if (isset($val[$q_key][$op_key])) {
                        $input_data[$q_key][$op_key] = $val[$q_key][$op_key];
                    }
                }
            } else {
                if (!isset($val[$q_key])) {
                    throw new BusinessException("第{$key}条数据{$q_key}字段缺失");
                }
                if ($q_val && $val[$q_key] == '') {
                    throw new BusinessException("第{$key}条数据{$q_key}字段值不得为空");
                }
                $input_data[$q_key] = $val[$q_key];
            }
        }
        return $input_data;
    }
}